package master;

import java.io.*;
import java.net.*;

class Master implements Runnable {
	public final static String ARQUIVO_CIFRADO = "cifrado.txt";
	public final static String ARQUIVO_DICIONARIO = "dicionario.txt";
	public final static int LISTEN_PORT = 6789;
	public final static String SUCESS_KEY = "FAESA";
	
	public static void main(String argv[]) throws Exception
	{
		Master master = new Master();
		master.run();
	}

	@Override
	public void run() {
		System.out.print("Trying to read files...");
		CypherReader reader = null;
		
		try {
			reader = new CypherReader(Master.ARQUIVO_DICIONARIO, Master.ARQUIVO_CIFRADO);
			System.out.println("done");
		} catch (FileNotFoundException e) {
			System.out.println(e.getMessage());
			return; // bica! \o/
		}
		ServerSocket welcomeSocket = null;
		System.out.print("Activating master...");
		try {
			welcomeSocket = new ServerSocket(Master.LISTEN_PORT);
			System.out.println("listening on " + Master.LISTEN_PORT);
		} catch (IOException e) {
			System.out.println("failed");
			return; // bica 2!!
		}
		
		SlaveChannel channel = null;
		System.out.print("Awaiting connection...");
		try {
			channel = SlaveChannel.accept(welcomeSocket);
			System.out.print("established");
		} catch (IOException e1) {
			System.out.println(e1.getMessage());
			return; // bica 3 o/
		}
		
		try {
			String text = reader.getText();
			while (reader.hasNext()) {
				String key = reader.nextKey();
				System.out.print("Using key " + key + "...");
				
				String decoded = channel.decrifrarTexto(text, key, Master.SUCESS_KEY);
				if (decoded == null || decoded.isEmpty()) {
					System.out.println("failed");
				}
				else {
					try {
						File file = new File("decifrado - " + key + ".txt");
						file.createNewFile();  
						
						BufferedWriter out = new BufferedWriter(new FileWriter(file.getAbsolutePath()));  
						out.write(decoded);
						out.close();
						
						System.out.println("created file " + file.getAbsolutePath());
					} catch (IOException ioex) {
						System.out.println("fail to create file");
					}
				}
			}
		} catch (IOException e) {
			System.out.println("unable to read files");
		}
		
		System.out.println("Done!");
	}
}